<script setup>
import Player from 'xgplayer'
import 'xgplayer/dist/index.min.css'
import { computed, getCurrentInstance, onMounted, ref } from "vue";
import { showConfirmDialog, showFailToast, showSuccessToast } from "vant";
import { QueryVideoList, UpdateVideoCount } from "@/api/home.js"
import { QueryUserLike, QueryUserCollect } from "@/api/user.js"
import Love from "@/components/Love/index.vue"

import useStore from "@/store"
import { HlsPlugin } from "xgplayer-hls";

const { homeStore, userInfo } = useStore()
const { proxy } = getCurrentInstance()

const playerList = ref([]) // 播放列表
const total = ref(0)
const params = ref({
	page: 1,
	pageSize: 6
})
const loveVisible = ref(false)
const pageX = ref(0)
const pageY = ref(0)
const isLike = ref(false)
const isCollect = ref(false)
const user = computed(() => userInfo?.userInfo)

let RefPlayer;
const percent = ref(0) // 进度条百分比值
const play = ref(false)

const getIsLike = async (index) => {
	try {
		const result = await QueryUserLike({ videoId: playerList.value[index].id })
		isLike.value = result.data.isLike
	} catch (e) {
	}
}

const getIsCollect = async (index) => {
	try {
		const result = await QueryUserCollect({ videoId: playerList.value[index].id })
		isCollect.value = result.data.isCollect
	} catch (e) {
	}
}

onMounted(() => {
	QueryVideoList(params.value).then(async res => {
		if (res.data.records && res.data.records.length) {
			playerList.value = res.data.records
			total.value = res.data.total
			await getIsLike(0)
			await getIsCollect(0)
			setTimeout(() => {
				homeStore.updateCurrentPlayer(playerList.value[0])
				formatVideo(0, playerList.value[0].videoUrl)
			}, 200)
		}
	})
})

// 格式化视频
const formatVideo = (id, url) => {
	RefPlayer = new Player({
		id: 'player' + id,
		url,
		fluid: true,
		autoplay: true,
		loop: true,
		videoInit: true,
		volume: 0, // 初始化时设置音量为 0，
		controls: false, // true/false决定是否使用底部控制栏，
		plugins: [HlsPlugin],
		closeVideoTouch: true,
		closeVideoClick: true,

		// poster: poster_c, // 封面图
		ignores: ['fullscreen', 'volume'], // 禁用播放和暂停按钮
		// ...具体参照 文档
	})

	RefPlayer.on('timeupdate', function (val) {
		//算出时间百分比的值
		if (val.currentTime && val.duration) {
			percent.value = (val.currentTime / val.duration) * 100
		}
	})

	RefPlayer.on('play', function (val) {
		//算出时间百分比的值
		play.value = true
	})
}

// 切换轮播事件
const changeSwipe = async (index) => {
	// 销毁上一个实例
	RefPlayer.destroy()
	// 进度条清零
	percent.value = 0;
	// 算出最大页码数
	const maxPage = Math.ceil(total.value / params.value.pageSize)
	if (params.value.page < maxPage && (index % (params.value.pageSize - 2)) == 0 && params.value.page == (playerList.value.length / params.value.pageSize)) {
		params.value.page += 1
		const res = await QueryVideoList(params.value)
		playerList.value.push(...res.data.records)
	}
	homeStore.updateCurrentPlayer(playerList.value[index])
	formatVideo(index, playerList.value[index].videoUrl)

	// 查询是否点赞
	await getIsLike(index)
	await getIsCollect(index)
}


let clickCount = 0;
const CLICK_THRESHOLD = 200; // 单位：毫秒
// 改变播放信息
const updatePlayerInfo = async (e) => {
	if (homeStore.showReview) {
		homeStore.updateShowReview(false)
		return
	}
	clickCount++;
	if (clickCount === 1) {
		setTimeout(() => {
			if (clickCount === 1) {
				// 单击处理逻辑
				// // 判断点击是否不为小功能块
				const flag = e.target.classList.contains("parent")
				if (flag) {
					if (RefPlayer.paused) {
						RefPlayer.play()
						play.value = true
					} else {
						RefPlayer.pause()
						play.value = false
					}
				}
			}
			// 无论单击还是双击，都需要重置计数器
			clickCount = 0;
		}, CLICK_THRESHOLD);
	} else if (clickCount === 2) {
		// 双击处理逻辑
		await likeHandler(e.clientX, e.clientY)
		// 重置计数器
		clickCount = 0;
	}

}


// 评论事件
const chatHandler = (e) => {
	homeStore.updateShowReview(true)
}

// 接受其他页面暂停视频
let status;
$bus.on("updatePlayStatus", (val) => {
	if (val == "to") {
		status = play.value
		play.value = false
		RefPlayer.pause()
	} else {
		if (status) {
			play.value = true
			RefPlayer.play()
			return
		}
		play.value = false
		RefPlayer.pause()
	}
})

// 关闭点赞事件
const closeLove = async () => {
	const index = playerList.value.findIndex(item => item.id === homeStore.currentPlayer.id)
	// 查询是否已点赞
	playerList.value[index].likes = isLike.value ? playerList.value[index].likes -= 1 : playerList.value[index].likes += 1
	await UpdateVideoCount({ videoId: homeStore.currentPlayer.id, type: 1, increase: !isLike.value })
	isLike.value = !isLike.value
}

// 点赞事件
const likeHandler = async (x, y) => {
	if (!user.value.id) return gotoLogin()
	pageX.value = x
	pageY.value = y
	if (!isLike.value) {
		loveVisible.value = true
	} else {
		await closeLove()
		showSuccessToast("已取消点赞")
	}
}

/*
* 用户收藏事件
* */
const userCollect = async () => {
	if (!user.value.id) return gotoLogin()
	const index = playerList.value.findIndex(item => item.id === homeStore.currentPlayer.id)
	// 查询是否已点赞
	playerList.value[index].collect = isCollect.value ? playerList.value[index].collect -= 1 : playerList.value[index].collect += 1
	await UpdateVideoCount({ videoId: homeStore.currentPlayer.id, type: 3, increase: !isCollect.value })
	isCollect.value = !isCollect.value
	if (!isCollect.value) showSuccessToast("已取消收藏")
}

// 前往登录方法
const gotoLogin = () => {
	showConfirmDialog({
		title: '提示',
		message:
			'是否要去往登录页面!!',
	})
		.then(() => {
			homeStore.updateShowReview(false)
			proxy.$router.push("/login")
			// on confirm
		})
		.catch(() => {
			// on cancel
		});
}

</script>

<template>
	<div class="home-height text-[#fff]" :class="{ 'content': homeStore.sendMsgIsFocus }">
		<van-swipe class="h-full" vertical :loop="false" :show-indicators="false" @change="changeSwipe">
			<van-swipe-item v-for="(item, index) in playerList">
				<div :id="'player' + index" class="player-container"
					:style="{ '--height': homeStore.showReview ? '600px' : '60px' }" @click="updatePlayerInfo">
					<!--内部展示信息盒子-->
					<div class="w-full h-full relative parent">
						<!--右侧视频信息展示-->
						<div class="absolute right-[10px] bottom-[50px] overflow-hidden like" v-show="!homeStore.showReview">
							<div class="relative">
								<!--头像-->
								<van-image width="50" height="50" round src="https://fastly.jsdelivr.net/npm/@vant/assets/cat.jpeg" />
								<!--<van-icon name="add" size="20" class="info-add" color="red"/>-->
							</div>
							<div class="flex flex-col items-center py-10" @click="likeHandler(200, 300)">
								<van-icon name="like" color="red" size="40" :style="{ animation: 'increase_scale 0.5s' }"
									v-if="isLike" />
								<van-icon name="like" color="#fff" size="40" :style="{ animation: 'increase_scale 0.5s' }" v-else />
								<span class="text-[12px]">{{ item.likes }}</span>
							</div>
							<div class="flex flex-col items-center py-10" @click.stop="chatHandler">
								<van-icon name="chat" color="#fff" size="40" />
								<span class="text-[12px]">{{ homeStore.currentPlayer.reply_size }}</span>
							</div>
							<div class="flex flex-col items-center py-10" @click="userCollect">
								<van-icon name="star" color="yellow" size="40" :style="{ animation: 'increase_scale 0.5s' }"
									v-if="isCollect" />
								<van-icon name="star" color="#fff" size="40" :style="{ animation: 'increase_scale 0.5s' }" v-else />
								<span class="text-[12px]">{{ item.collect }}</span>
							</div>
						</div>
						<div class="bottom-[5px] w-full left-0 absolute" v-show="!homeStore.showReview">
							<van-progress :percentage="percent" pivot-color="#ffffff" pivot-text=""
								color="linear-gradient(to right, #be99ff, #7232dd)" />
						</div>
					</div>
				</div>
			</van-swipe-item>
		</van-swipe>
		<!--暂停页面-->
		<!--<div class="pause" v-if="!play">-->
		<!--  <van-icon name="play" size="40"/>-->
		<!--</div>-->
		<Love v-model:visible="loveVisible" :x="pageX" :y="pageY" @close="closeLove"></Love>
	</div>
</template>

<style scoped lang="scss">
.content {
	position: relative;
	top: 392px;
}

.player-container {
	height: calc(100vh - var(--height)) !important;
	padding-top: 0px !important;
	transition: all 0.2s;
}


.info-add {
	position: absolute;
	bottom: -3px;
	left: 50%;
	transform: translateX(-50%);
}

.py-10 {
	padding: 10px 0 !important;
}

//.pause {
//  position: absolute;
//  left: 50%;
//  top: 50%;
//  transform: translate(-50%, -50%);
//}

//:deep(.xgplayer.xgplayer-mobile .xgplayer-start) {
//  display: none;
//}</style>
